import 'dart:async';
import 'dart:typed_data';

import 'package:meta/meta.dart';

import '../../../sentry_flutter.dart';
import '../../replay/scheduled_recorder.dart';
import '../sentry_safe_method_channel.dart';

/// HarmonyOS implementation of the scheduled screenshot replay recorder.
///
/// Unlike Android (JNI + Bitmap), OHOS uses the ETS layer to perform the
/// actual replay capture. This recorder focuses on capturing screenshots on
/// a schedule and passing them to the native side through the existing
/// MethodChannel handled by ETS (`SentryFlutterPlugin.ets`).
@internal
class OhosReplayRecorder extends ScheduledScreenshotRecorder {
  // @internal // visible for testing, used by SentryNativeOhos
  // static OhosReplayRecorder Function(SentryFlutterOptions) factory =
  //     OhosReplayRecorder.new;

  final SentrySafeMethodChannel _channel;
  final String _cacheDir;

  OhosReplayRecorder(
      super.config, super.options, this._channel, this._cacheDir) {
    super.callback = _addReplayScreenshot;
  }

  Future<void> _addReplayScreenshot(
      ScreenshotPng screenshot, bool isNewlyCaptured) async {
    print("_addReplayScreenshot start");
    final timestamp = screenshot.timestamp.millisecondsSinceEpoch;
    final filePath = "$_cacheDir/$timestamp.png";

    options.logger(
        SentryLevel.debug,
        '$logName: saving ${isNewlyCaptured ? 'new' : 'repeated'} screenshot to'
            ' $filePath (${screenshot.width}x${screenshot.height} pixels, '
            '${screenshot.data.lengthInBytes} bytes)');
    try {
      await options.fileSystem
          .file(filePath)
          .writeAsBytes(screenshot.data.buffer.asUint8List(), flush: true);

      await _channel.invokeMethod(
        'addReplayScreenshot',
        {'path': filePath, 'timestamp': timestamp},
      );
    } catch (error, stackTrace) {
      print("_addReplayScreenshot error = ${_addReplayScreenshot}");
      options.logger(
        SentryLevel.error,
        '$logName: native call `addReplayScreenshot` failed',
        exception: error,
        stackTrace: stackTrace,
      );
      if (options.automatedTestMode) {
        rethrow;
      }
    }
  }

  // @override
  // Future<void> start() async {
  //   await super.start();
  // }
  //
  // @override
  // Future<void> stop() async {
  //   await super.stop();
  // }
  //
  // Future<void> _addReplayScreenshot(
  //     ScreenshotPng screenshot, bool isNewlyCaptured) async {
  //   final timestamp = screenshot.timestamp.millisecondsSinceEpoch;
  //
  //   try {
  //     // Convert RGBA buffer into a byte list; ETS/native side will handle
  //     // encoding/aggregation as appropriate.
  //     final data = await screenshot.data;
  //     final bytes = data.buffer.asUint8List();
  //
  //     await options.fileSystem
  //         .file(filePath)
  //         .writeAsBytes(screenshot.data.buffer.asUint8List(), flush: true);
  //
  //     await _channel.invokeMethod(
  //       'addReplayScreenshot',
  //       {'path': filePath, 'timestamp': timestamp},
  //     );
  //
  //     // options.log(
  //     //   SentryLevel.debug,
  //     //   '$logName: captured screenshot ('
  //     //   '${screenshot.width}x${screenshot.height} pixels, '
  //     //   '${bytes.lengthInBytes} bytes, ts=$timestamp)',
  //     // );
  //
  //     // On OHOS, replay capture is executed natively. We only need to
  //     // ensure the replay integration has enough context; the actual
  //     // triggering is driven from the ETS plugin via `captureReplay`.
  //     // If in the future we add a raw image forwarding API, this is where
  //     // we'd invoke it through MethodChannel.
  //   } catch (error, stackTrace) {
  //     // options.log(
  //     //   SentryLevel.error,
  //     //   '$logName: OHOS replay screenshot processing failed',
  //     //   exception: error,
  //     //   stackTrace: stackTrace,
  //     // );
  //     if (options.automatedTestMode) {
  //       rethrow;
  //     }
  //   }
  // }
}


